package com.demo.rydemo.d_user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.demo.rydemo.d_user.entity.DUser;
import com.demo.rydemo.d_user.service.IDUserService;
import com.demo.rydemo.d_user.vo.DUserVo;
import com.demo.rydemo.jwt.model.JwtUser;
import com.demo.rydemo.jwt.model.JwtUserEnum;
import com.demo.rydemo.jwt.util.JwtUtil;
import com.demo.rydemo.result.AjaxResult;
import com.demo.rydemo.result.CoreController;
import com.fasterxml.jackson.databind.json.JsonMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ry
 * @since 2020-07-31
 */
@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/d_user/d-user")
@Slf4j
public class DUserController extends CoreController {

    @Autowired
    AjaxResult ajaxResult;

    static final String FORM_LOGIN = "form";

    static final String SHIRO_LOGIN = "shiro";

    @Value("${com.demo.loginMode}")
    String loginMode;

    @Autowired
    IDUserService idUserService;

    /**
     * 用户登录(多种登录方式,多因子认证)
     * @param user
     * @return
     */
    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    AjaxResult<String> login(@RequestBody DUser user){
        //判断登录方式 用户名密码登录-form  第三方登录-oauth2
        if(SHIRO_LOGIN.equals(loginMode)){
            //认证
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUserAccount(),
                    user.getUserPassword());

            try{
                subject.getPrincipal();
                subject.login(token);
            }catch (AuthenticationException e){
                return ajaxResult.error(e.getMessage());
            }

        }
        else{
            //其他登录认证方式
            //先判断是否登录，如果可以登录 则 传递 JWT
            Md5Hash md5Hash =new Md5Hash(user.getUserPassword(),user.getUserAccount());
            log.info("md5Hash:{0}",md5Hash.toString());
            user.setUserPassword(md5Hash.toString());
            DUser d =  idUserService.getOne(new QueryWrapper<DUser>().eq("user_account",user.getUserAccount())
            .eq("user_password",user.getUserPassword()));
            if(d != null){
                //记录token
                JwtUser jwtUser = JwtUser.builder().userId(Long.parseLong(d.getUserId().toString())).roles("user")
                        .userLoginCode("haha").userEnum(JwtUserEnum.WECHAT).build();
                jwtUser.putExtInfo("app_token", "abcd");

                String token = JwtUtil.getInstance(JwtUtil.getDefaultKey()).signJwtUser(jwtUser);
                //传递token和当前用户名到前端。
                Map map = new HashMap();
                map.put("token",token);
                map.put("nowUser",user.getUserAccount());
                return ajaxResult.success(map);
            }

        }

        return ajaxResult.success("登录成功");
    }


    /**
     * 获取用户列表
     * @param dUserVo
     * @return
     */
    @GetMapping("/getUserList")
    AjaxResult<List<DUser>> getUserList(DUserVo dUserVo){
        IPage page = idUserService.getUserList(dUserVo);
        return ajaxResult.success(page);
    }

    @PostMapping("/addUser")
    AjaxResult addUser(@RequestBody DUserVo dUserVo){
        Boolean flag = false;
        flag = idUserService.addUser(dUserVo);
        if(flag) {
            return ajaxResult.success(flag);
        }else{
            return ajaxResult.error("注册失败,请联系管理员");
        }
    }

    @PostMapping("/edituser")
    AjaxResult editUser(@RequestBody DUserVo dUserVo){
        Boolean flag = false;
        flag = idUserService.editUser(dUserVo);
        if(flag) {
            return ajaxResult.success(flag);
        }else{
            return ajaxResult.error("修改失败,请联系管理员");
        }
    }


    @ApiOperation("通过用户账号去获取用户列表")
    @GetMapping("/getUserListByAccount")
    AjaxResult getUserListByAccount(String userAccount){
        QueryWrapper qw = new QueryWrapper();
        qw.likeRight("user_account",userAccount+"%");
        return ajaxResult.success(idUserService.list(qw));
    }

}
